<template>
  <div style="width: 100%;height: 100%;position: relative;padding-top: 54px">
    <v-app-bar flat
               app
               color="white"
               style="z-index: 1;padding-top: 6px;left: 0;"
               height="54"
               absolute
    >
      <v-toolbar-title>文章 Article</v-toolbar-title>
      <v-divider
        class="mx-4"
        inset
        vertical
      ></v-divider>
    </v-app-bar>
    <v-tabs>
      <v-tab>已发布</v-tab>
      <v-tab>草稿箱</v-tab>
      <v-tab>置顶</v-tab>
      <v-tab-item style="padding: 20px">
        <v-data-table
          :headers="headers"
          :items="publishedArticleList"
          :page.sync="publishedPagination.page"
          disable-sort
          hide-default-footer
          :loading="publishedLoading"
          loading-text="拼命加载... 请稍等"
          class="elevation-1 mb-4"
        >
          <template v-slot:item.createTime="{ item }">
            {{ item.createTime.split('.')[0].split('T').join(' ') }}
          </template>
          <template v-slot:item.updateTime="{ item }">
            {{ item.updateTime.split('.')[0].split('T').join(' ') }}
          </template>

          <template v-slot:item.top="{ item }">
            <div class="d-flex">
              <v-switch
                v-model="item.top"
                inset
                disabled
                style="margin-top: 0"
                color="info"
                :false-value="0"
                :true-value="1"
                hide-details
              ></v-switch>
              <v-btn
                fab
                dark
                x-small
                color="cyan"
                @click="topArticle(item)"
              >
                <v-icon dark>mdi-pencil</v-icon>
              </v-btn>
            </div>

          </template>

          <template v-slot:item.actions="{ item }">
            <v-btn small class="mr-2" color="cyan" dark @click="editItem(item)">编辑
              <v-icon
                small
              >
                mdi-pencil
              </v-icon>
            </v-btn>
            <v-btn small color="error" dark @click="deleteItem(item,publishedArticleList)">删除
              <v-icon
                small
              >
                mdi-delete
              </v-icon>
            </v-btn>
          </template>
          <template v-slot:no-data>
            暂时木有内容
          </template>
        </v-data-table>

        <div class="text-center">
          <v-pagination
            v-model="publishedPagination.page"
            :total-visible="6"
            :length="Math.ceil(publishedTotal/publishedPagination.limit)"
          ></v-pagination>
        </div>
      </v-tab-item>
      <v-tab-item style="padding: 20px">
        <v-data-table
          :headers="headers"
          :items="unpublishedArticleList"
          :page.sync="unpublishedPagination.page"
          disable-sort
          hide-default-footer
          :loading="unpublishedLoading"
          loading-text="拼命加载... 请稍等"
          class="elevation-1 mb-4"
        >
          <template v-slot:item.createTime="{ item }">
            {{ item.split('.')[0].split('T').join(' ') }}
          </template>
          <template v-slot:item.updateTime="{ item }">
            {{ item.split('.')[0].split('T').join(' ') }}
          </template>
          <template v-slot:item.actions="{ item }">
            <v-icon
              small
              class="mr-2"
              @click="editItem(item)"
            >
              mdi-pencil
            </v-icon>
            <v-icon
              small
              @click="deleteItem(item,unpublishedArticleList)"
            >
              mdi-delete
            </v-icon>
          </template>
          <template v-slot:no-data>
            暂时木有内容
          </template>
        </v-data-table>

        <div class="text-center">
          <v-pagination
            v-model="publishedPagination.page"
            :total-visible="6"
            :length="Math.ceil(publishedTotal/publishedPagination.limit)"
          ></v-pagination>
        </div>
      </v-tab-item>

      <v-tab-item style="padding: 20px">
        <v-data-table
          :headers="topHeaders"
          :items="topArticleList"
          disable-sort
          hide-default-footer
          :loading="topLoading"
          loading-text="拼命加载... 请稍等"
          class="elevation-1 mb-4"
        >
          <template v-slot:item.createTime="{ item }">
            {{ item.createTime.split('.')[0].split('T').join(' ') }}
          </template>
          <template v-slot:item.updateTime="{ item }">
            {{ item.updateTime.split('.')[0].split('T').join(' ') }}
          </template>
          <template v-slot:item.top="{ item }">
            <div class="d-flex">
              <v-switch
                v-model="item.top"
                inset
                disabled
                style="margin-top: 0"
                color="info"
                :false-value="0"
                :true-value="1"
                hide-details
              ></v-switch>
              <v-btn
                fab
                dark
                x-small
                color="cyan"
                @click="topArticle(item)"
              >
                <v-icon dark>mdi-pencil</v-icon>
              </v-btn>
            </div>

          </template>
          <template v-slot:no-data>
            暂时木有内容
          </template>
        </v-data-table>
      </v-tab-item>
    </v-tabs>

    <v-dialog v-model="topArticleDialog" max-width="500px">
      <v-card>
        <v-card-title>
          <span class="headline">置顶</span>
        </v-card-title>

        <v-card-text v-if="editedItem">
          <v-container>
            <v-row>
              <v-col cols="12" sm="12" md="12">
                <v-switch
                  v-model="editedItem.top"
                  inset
                  label="开启置顶"
                  color="info"
                  :true-value="1"
                  :false-value="0"
                  hide-details
                ></v-switch>
              </v-col>
              <v-col cols="12" sm="12" md="12">
                <v-text-field v-model="editedItem.topIndex"
                              label="置顶权重"></v-text-field>
              </v-col>
            </v-row>
          </v-container>
        </v-card-text>

        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="pink darken-1" text @click="close">取消</v-btn>
          <v-btn color="blue darken-1" text @click="saveArticle">确认</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script>
import { DeleteArticle, GetArticle, GetArticleCount } from '../api/blog-api'
import util from '../libs/util'
import { mapState } from 'vuex'
import { GetTopArticle, UpdateOneArticle } from '@/api/blog-api'

const UNPUBLISHED = 0
const PUBLISHED = 1
export default {
  name: 'ArticleManager',
  computed: {
    ...mapState('milk/user', ['user'])
  },
  data: () => ({
    publishedLoading: true,
    unpublishedLoading: true,
    topLoading: true,
    publishedArticleList: [],
    unpublishedArticleList: [],
    topArticleList: [],
    headers: [
      {
        text: '标题',
        align: 'start',
        value: 'title',
      },
      {
        text: '分类',
        value: 'category'
      },
      {
        text: '标签',
        value: 'tag'
      },
      {
        text: '阅读数',
        value: 'viewNum'
      },
      {
        text: '创建日期',
        value: 'createTime'
      },
      {
        text: '最近更新',
        value: 'updateTime'
      },
      {
        text: '置顶',
        value: 'top'
      },
      {
        text: '操作',
        value: 'actions',
      },
    ],
    topHeaders: [
      {
        text: '标题',
        align: 'start',
        value: 'title',
      },
      {
        text: '分类',
        value: 'category'
      },
      {
        text: '标签',
        value: 'tag'
      },
      {
        text: '阅读数',
        value: 'viewNum'
      },
      {
        text: '置顶',
        value: 'top'
      }
    ],
    publishedPagination: {
      page: 1,
      limit: 12
    },
    publishedTotal: 0,
    unpublishedPagination: {
      page: 1,
      limit: 12
    },
    unpublishedTotal: 0,
    editedItem: null,
    editedIndex: -1,
    editing: false,
    topArticleDialog: false
  }),
  mounted () {
    if (this.user.userRole === 0) {
      // 获取发布文章数量
      this.getArticleCount(PUBLISHED).then(res => {
        this.publishedTotal = res.data
        this.getPublishedArticle(this.publishedPagination)
      }).catch(err => {
      })

      // 获取草稿文章数量
      this.getArticleCount(UNPUBLISHED).then(res => {
        this.unpublishedTotal = res.data
        this.getUnPublishedArticle(this.unpublishedPagination)
      }).catch(err => {
      })

      this.getTopArticle()
    }
  },
  methods: {
    topArticle (article) {
      // 置顶文章
      this.publishedArticleList.some((_article,index)=>{
        if(article._id===_article._id){
          this.editedIndex = index
          return true
        }
      })
      // this.editedIndex = this.publishedArticleList.indexOf(article)
      this.editedItem = Object.assign({}, article)
      this.topArticleDialog = true
    },

    close () {
      this.editing = false
      this.editedIndex = -1
      this.editedItem = null
      this.topArticleDialog = false
    },

    saveArticle () {
      this.editing = true
      // 更新文章
      UpdateOneArticle(this.editedItem).then(res => {
        // console.log(this.editedIndex)
        if (this.editedIndex > -1) {
          Object.assign(this.publishedArticleList[this.editedIndex], res.data)
        }
        this.getTopArticle()
      }).catch(err => {
        console.log(err)
      }).finally(() => {
        this.close()
      })
    },

    getArticleCount (type) {
      return GetArticleCount({ published: type })
    },

    // 获取置顶文章
    getTopArticle () {
      this.topLoading = true
      GetTopArticle().then(res => {
        this.topArticleList = res.data
      }).catch(err => {
        console.log(err)
      }).finally(() => {
        this.topLoading = false
      })
    },

    // 获取已发布的文章
    getPublishedArticle (pagination = {}, query = {}) {
      this.publishedLoading = true
      query.published = PUBLISHED
      GetArticle({
        ...pagination, ...query
      }).then(res => {
        this.publishedArticleList = res.data
      }).catch(err => {
        console.log(err)
      }).finally(() => {
        this.publishedLoading = false
      })
    },

    // 获取草稿
    getUnPublishedArticle (pagination = {}, query = {}) {
      this.unpublishedLoading = true
      query.published = UNPUBLISHED
      GetArticle({
        ...pagination, ...query
      }).then(res => {
        this.unpublishedArticleList = res.data
      }).catch(err => {
        console.log(err)
      }).finally(() => {
        this.unpublishedLoading = false
      })
    },

    editItem (item) {
      util.open(window.location.origin + '/article/' + item._id)
    },

    deleteItem (item, list) {
      const index = list.indexOf(item)
      if (confirm('确认删除该文章？')) {
        DeleteArticle(item).then(res => {
          list.splice(index, 1)
        }).catch(err => {
          console.log(err)
        })
      }
    },
  }
}
</script>

<style scoped>

</style>
